<?php 

namespace App\Libs;

use Qiniu\Auth;
use Qiniu\Processing\PersistentFop;
use Qiniu\Storage\BucketManager;

// 引入上传类
use Qiniu\Storage\UploadManager;
use Illuminate\Support\Facades\Log;

//七牛相关调用
class QiniuLibrary {

	const accessKey = '80P_OhFKyB_RhAUEQ37ifXlHG2_IkDXr64VNm_rb';
	const secretKey = '6-OyvCWml5b-0rsjngzRVNJvf4cQ4G9Sdz3jRGhy';

	const bucket    = 'zhen22-assets';

	/**
	 * 创建连接
	 * @return Auth
	 */
	public static function Auth()
	{
		//$accessKey = getenv('QINIU_ACCESS_KEY');
        //$secretKey = getenv('QINIU_SECRET_KEY');
		return new Auth(self::accessKey, self::secretKey);
	}


	/**
	 * 获取toke
	 * @param $bucket
	 * @return string
	 */
	public static function Token($bucket)
	{
		$auth = self::Auth();
		return $auth->uploadToken($bucket);
	}


	/**
	 * 输出配置
	 * @return \Qiniu\Config
	 */
	public static function Config()
	{
		return new \Qiniu\Config();
	}


	/**
	 * 持久化操作
	 * @return PersistentFop
	 */
	public static function PersistentFop()
	{
		return new PersistentFop(self::Auth(), self::Config());
	}

	/**
	 * 空间管理操作
	 * @return BucketManager
	 */
	public static function BucketManager()
	{
		return new BucketManager(self::Auth(), self::Config());
	}

	/**
	 * 上传
	 */
	public static function upload($filePath, $key)
	{
	   try{
            //请求七牛上传接口的token
			$token = self::Token('sls-assets');
			// 初始化 UploadManager 对象并进行文件的上传。
			$uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传。
			$file = file_get_contents($filePath);
			list($ret, $err) = $uploadMgr->put($token, $key, $file);
			if ($err !== null) {
				return ['code'=> 0, 'url'=>''];
			} else {
				return ['code'=> 1, 'url'=>'https://file.doufangsls.com/'.$key];
			}	
	   }catch(\Exception $e){
            Log::error('上传失败:'.$e->getMessage());
            return ['code'=> 0, 'url'=>''];
	   }	
		
	}
}
